package me.jzn.alib.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;

import androidx.annotation.IdRes;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.Field;

import me.jzn.core.exceptions.UnableToRunHereException;
import me.jzn.core.utils.CommUtil;

public class AuxUtil {
    public static void setOnClickListener(OnClickListener listener, View... views) {
        for (View view : views) {
            view.setOnClickListener(listener);
        }
    }

    public static void setOnClickListener(OnClickListener listener, ViewBinding bind, Class<? extends View>... types) {
        for (Field field : bind.getClass().getFields()) {
            Class<?> fieldType = field.getType();
            for (Class<? extends View> type : types) {
                if (CommUtil.isSubClass(fieldType, type)) {
                    try {
                        View view = (View) field.get(bind);
                        view.setOnClickListener(listener);
                    } catch (IllegalAccessException e) {
                        throw new UnableToRunHereException("bind字段都是public的");
                    }
                }
            }
        }
    }

    /**
     * @see .setOnClickListener(ViewBinding , OnClickListener );
     */
    @Deprecated
    public static void setAsOnlickListener(Activity activity, @IdRes int... resids) {
        if (activity instanceof OnClickListener) {
            OnClickListener listener = (OnClickListener) activity;
            for (int id : resids) {
                activity.findViewById(id).setOnClickListener(listener);
            }
        }
    }

    /**
     * @see .setAsOnlickListener(ViewBinding , OnClickListener );
     */
    @Deprecated
    public static void setAsOnlickListener(View view, @IdRes int... resids) {
        if (view instanceof OnClickListener) {
            OnClickListener listener = (OnClickListener) view;
            for (int id : resids) {
                view.findViewById(id).setOnClickListener(listener);
            }
        }
    }

    /**
     * @see .setAsOnlickListener(ViewBinding , OnClickListener );
     */
    @Deprecated
    public static void setAsOnlickListener(View view, OnClickListener listener, @IdRes int... resids) {
        for (int id : resids) {
            view.findViewById(id).setOnClickListener(listener);
        }
    }

    public static final void startActivity(Context packageContext, Class<? extends Activity> target) {
        packageContext.startActivity(new Intent(packageContext, target));
    }

    public static final void startActivity(Fragment fragment, Class<? extends Activity> target) {
        startActivity(fragment.getActivity(), target);
    }

    public static final void startActivity(View view, Class<? extends Activity> target) {
        startActivity(view.getContext(), target);
    }
}
